package org.example.zhihuan.services;

import org.example.zhihuan.services.projectException.*;
import org.example.zhihuan.util.Db;

import java.sql.ResultSet;
import java.util.List;

//潘思航
public class User {
    public final static int NORMAL = 0;
    public final static int BAN = 1;
    public final static int CANCEL = 2;

    private boolean isSaved = false;

    private int userId;             //用户id
    private String userName;        //用户名
    private String userPsw;         //用户密码
    private double userMoney;       //用户余额
    private int userState;      //用户状态    封禁和正常
    private int userCredit;         //用户信誉


    public int getUserState() {
        return userState;
    }

    public boolean isSaved() {
        return isSaved;
    }

    public int getUserId() {
        return userId;
    }

    public String getUserPsw() {
        return userPsw;
    }

    public double getUserMoney() {
        return userMoney;
    }

    public int getUserCredit() {
        return userCredit;
    }

    public String getUserName() {
        return userName;
    }

    /**
     * 持久化
     */
    private void save() {
        StringBuilder sb = new StringBuilder();
        if (isSaved) {
            sb.append("update user set ")
                    .append(" user_psw = '").append(userPsw).append("',")
                    .append(" user_name = '").append(userName).append("',")
                    .append(" user_money = ").append(userMoney).append(",")
                    .append(" user_state = ").append(userState).append(",")
                    .append(" user_credit = ").append(userCredit).
                    append(" where user_id = ").append(userId);
        } else {
            sb.append("insert into user (user_psw,user_name,user_money,user_state,user_credit) values" +
                    " ('").append(userPsw).append("','")
                    .append(userName).append("',").append(userMoney).append(",")
                    .append(userState).append(",").append(userCredit).append(")");
            isSaved = true;
        }
        Db.execute(sb.toString());
    }

    /**
     * User 是否被ban
     * @param userId
     * @return
     */
    public static boolean userIsBan(int userId){
        if (User.getUser(userId).getUserState()==BAN){
            return true;
        }else {
            return false;
        }
    }

    /**
     * UserGet ById
     *
     * @param userId
     * @return
     */
    public static User getUser(int userId) {
        User user = new User();
        Db.read("select * from user where user_id = " + userId, set -> {
            if (set.next()) {
                user.userId = set.getInt("user_id") ;
                user.userName = set.getString("user_name");
                user.userState = set.getInt("user_state");
                user.userCredit = set.getInt("user_credit");
                user.userPsw = set.getString("user_psw");
                user.userMoney = set.getDouble("user_money");
                user.isSaved = true;
            }
            return null;
        });
        return user;
    }

    /**
     * UserGet ByName
     * @param userName
     * @return
     */
    public static User getUser(String userName) {
        User user = new User();
        Db.read("select * from user where user_name = '" + userName+"' ", set -> {
            if (set.next()) {
                user.userId = set.getInt("user_id") ;
                user.userName = set.getString("user_name");
                user.userState = set.getInt("user_state");
                user.userCredit = set.getInt("user_credit");
                user.userPsw = set.getString("user_psw");
                user.userMoney = set.getDouble("user_money");
                user.isSaved = true;
            }
            return null;
        });
        return user;
    }

    /**
     * 注册
     *
     * @param userPsw
     * @param userName
     * @return
     */
    public static User register(String userName, String userPsw) {
        if (userIsSaved(userName)) {
            throw new UserIsSavedException("用户名存在");
        }
        if (User.userIsBan(User.getUser(userName).userId)){
            throw new UserStateException("用户不可用");
        }
        User user = new User();
        user.userName = userName;
        user.userPsw = userPsw;
        user.save();
        return user;
    }

    /**
     * User id存在
     *
     * @param userId
     * @return
     */
    public static boolean userIsSavedById(int userId) {
        return Db.read("select 1 from user where user_id=" + userId , ResultSet::next);
    }

    /**
     * User Name存在
     *
     * @param userName
     * @return
     */
    public static boolean userIsSaved(String userName) {
        return Db.read("select 1 from user where user_name='" + userName + "'", ResultSet::next);
    }

    /**
     * 登录
     *
     * @param userName
     * @param userPsw
     * @return
     */
    public static boolean login(String userName, String userPsw) {
        User user = User.getUser(userName);
        if (!User.userIsSaved(user.userName)){
            throw new UserIsSavedException("用户不存在");
        }
        if(User.userIsBan(user.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (user.getUserPsw().equals(userPsw)){
            return true;
        }
        return false;
    }


    /**
     * 用户创建商品
     *
     * @param goodsName
     * @param goodsType
     * @param price
     * @param goodsContent
     * @return
     */
    public boolean createGoods(String goodsName, int goodsType, double price, String goodsContent) {
        if (!User.userIsSaved(this.userName)){
            throw new UserIsSavedException("用户不存在");
        }
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
            Goods.createGoods(goodsName, goodsType, price, goodsContent, this.userId);
            return true;
    }

    /**
     * 上架商品
     *
     * @param goodsId
     * @return
     */
    public boolean userGoodsUp(int goodsId) {
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (Goods.goodsIdExist(goodsId)) {
            Goods goods = Goods.getGoods(goodsId);
            goods.goodsUp();
            return true;
        }
        throw new GoodsExistException("商品id不存在");
    }

    /**
     * User下架商品
     *
     * @param goodsId
     * @return
     */
    public boolean userGoodsDown(int goodsId) {
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (Goods.goodsIdExist(goodsId)) {
            Goods goods = Goods.getGoods(goodsId);
            goods.goodsDown();
            return true;
        }
        throw new GoodsExistException("商品id不存在");
    }

    /**
     * User创建订单
     *
     * @return
     */
    public boolean userCreateOrder(int sellerId, List<Integer> sellGoods, List<Integer> buyGoods) {
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        Order.orderCreate(sellerId,this.userId,sellGoods,buyGoods);
        return true;
    }

    /**
     * 用户拒绝交易
     *
     * @return
     */
    private boolean userOrderRefuse(int orderId) {
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (!Order.orderIdExist(orderId)) {
            throw new OrderExistException("订单不存在");
        }
        Order or = Order.getOrderById(orderId);
        or.orderDeal(false,orderId);
        return true;
    }

    /**
     * User同意订单
     * @param orderId
     * @return
     */
    public boolean userOrderDeal(int orderId){
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (!Order.orderIdExist(orderId)) {
            throw new OrderExistException("订单不存在");
        }
        Order or = Order.getOrderById(orderId);
        or.orderDeal(true,orderId);
        return true;
    }

    /**
     * User修改商品
     *
     * @param goodsId
     * @return
     */
    public boolean userModifyGoods(int goodsId, String goodsName, int goodsType, double price, String goodsContent) {
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if (Goods.goodsIdExist(goodsId)) {
            Goods goods = Goods.getGoods(goodsId);
            goods.modify(goodsName, goodsType, price, goodsContent);
            return true;
        }
        throw new GoodsExistException("商品id不存在");
    }

    /**
     * User注销
     *
     * @return
     */
    public boolean userCancel(boolean cancel) {
        if(this.userState !=NORMAL){
            throw new UserStateException("用户状态不可用");
        }
        if (cancel) {
            this.userState = CANCEL;
            this.save();
            return true;
        }else {
            return false;
        }
    }

    /**
     * User禁用
     *
     * @param ban
     * @return
     */
    public boolean userBan(boolean ban) {
        if(this.userState !=NORMAL){
            throw new UserStateException("用户状态不可用");
        }
        if (ban) {
            this.userState = BAN;
            this.save();
            return true;
        }else {
         return false;
        }
    }

    /**
     * User删除评论
     * @param assId
     * @return
     */
    public boolean userAssDelete(int assId){
        if(User.userIsBan(this.userId)){
            throw new UserStateException("用户已封禁");
        }
        if(!Assessment.assIdExist(assId)){
            throw new AssIdExistException("评论不存在");
        }
        Assessment.getAssessment(assId).assUserDelete(this.userId);
        return true;
    }

}
